package org.raymond.iworks.study.example;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.junit.jupiter.api.Test;
import org.raymond.iworks.core.config.BaseConfiguration;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
public class JsonTest {

    public ObjectMapper objectMapper(){
        ObjectMapper objectMapper = BaseConfiguration.uniqueMapper();
        return objectMapper;
    }

    @Test
    public void test01() throws JsonProcessingException, ParseException {
        Demo d0 = new Demo();
        d0.setName("diablo");
        d0.setAge(12);
        d0.setBirthDay(DateUtils.parseDate("2013-09-07 00:12:15"));
        d0.setIs(new int[]{1,2,3,5,7});
        ObjectMapper mapper = objectMapper();
        String s1 = mapper.writeValueAsString(d0);
        Demo d1 = mapper.readValue(s1, Demo.class);

        String s2 = "{\"name\":\"diablo1\", \"age\":null, 'days':null, hello:'123'}";
        Demo d2 = mapper.readValue(s2, Demo.class);
        log.info("{}, {}, {}, {}, {}", s1, d1, s2, d2, mapper.writeValueAsString(d2));
    }

    @Getter
    @Setter
    private static class Demo{
        private String name;
        private int age;
        private long days;
        private Date birthDay;
        private int[] is;
    }

    @Test
    public void test1() throws JsonProcessingException {
        ObjectMapper objectMapper = objectMapper();
        String s = "{username:'diablo', password:123456}";
        LinkedHashMap requestMap = objectMapper.readValue(s, LinkedHashMap.class);
        log.info("{}", requestMap);
        MultiValueMap multiValueMap = new LinkedMultiValueMap();
        MapUtils.multiValueMap(requestMap);
    }

    @Test
    public void test02(){
        String s = "[{\"acct\":\"1\"}, {\"acct\":\"2\"}]";
        s = "[{\"acct\":\"1\"}]";
        List<String> vals = JSONUtil.parseArray(s).stream().map(o->JSONUtil.parseObj(o).getStr("acct")).collect(Collectors.toList());
        log.info("{}", vals);
        StringBuilder sb= new StringBuilder();
        vals.stream().forEach(e->{
            sb.append(e).append(",");
        });
        s = sb.substring(0, sb.length()-1);
        log.info("{}", s);
        /*
        JSONUtil.parseArray(s).stream().forEach(e->{
            log.info("{}", e);
        });*/
    }


    @Test
    public void test03(){
        Map<String, String> m = new HashMap<>();
        Map<String, String> m0 = new HashMap<>();
        m.put("d229-63f7817a-cf-0", "123");
        log.info("{}", JSONUtil.toJsonStr(m));
    }
}
